package com.framework.spring.mybatis.util;

import com.framework.spring.mybatis.config.MyMapperScan;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.config.BeanDefinitionHolder;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.type.AnnotationMetadata;

import java.util.Map;
import java.util.Set;

@Slf4j(topic = "e")
public class MyImportBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar {

	@Override
	public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
		log.info("MyImportBeanDefinitionRegistrar registerBeanDefinitions");
//		BeanDefinition amapperBeanDefinition = BeanDefinitionBuilder.genericBeanDefinition(AMapper.class).getBeanDefinition();
//		BeanDefinition tmapperBeanDefinition = BeanDefinitionBuilder.genericBeanDefinition(TMapper.class).getBeanDefinition();
//		Map<String, BeanDefinition> beanDefinitionMap = new HashMap<>();
//		beanDefinitionMap.put("amapper", amapperBeanDefinition);
//		beanDefinitionMap.put("tmapper", tmapperBeanDefinition);
//
//		for (String key : beanDefinitionMap.keySet()) {
//			AbstractBeanDefinition beanDefinition = (AbstractBeanDefinition) beanDefinitionMap.get(key);
//			Class<?> beanClass = beanDefinition.getBeanClass();
//			log.info("before:{}", beanDefinition.getBeanClass().getSimpleName());
//			beanDefinition.setBeanClass(MyFactoryBean.class);
//			log.info("after:{}", beanDefinition.getBeanClass().getSimpleName());
//			beanDefinition.getPropertyValues().addPropertyValue("mapperInterface", beanClass);
//			registry.registerBeanDefinition(key, beanDefinition);
//		}

		Map<String, Object> annotationAttributes = importingClassMetadata.getAnnotationAttributes(MyMapperScan.class.getName());
		String value = (String) annotationAttributes.get("value");

		// 完成扫描
		Set<BeanDefinitionHolder> beanDefinitionHolders = scan(registry, value);
		for (BeanDefinitionHolder beanDefinitionHolder : beanDefinitionHolders) {
			AbstractBeanDefinition beanDefinition = (AbstractBeanDefinition) beanDefinitionHolder.getBeanDefinition();
			String beanClass = beanDefinition.getBeanClassName();
			log.info("before:{}", beanDefinition.getBeanClassName());
			beanDefinition.setBeanClass(MyFactoryBean.class);
			log.info("after:{}", beanDefinition.getBeanClassName());
			beanDefinition.getPropertyValues().addPropertyValue("mapperInterface", beanClass);
		}

	}

	public Set<BeanDefinitionHolder> scan(BeanDefinitionRegistry registry, String scanPackage) {
		MyMapperScaner mapperScaner = new MyMapperScaner(registry, false);
		mapperScaner.registerDefaultFilters();
//		mapperScaner.scan("com.framework.spring.mybatis.dao");
		return mapperScaner.doScan(scanPackage);
	}
}
